'''
Created on 2009-11-17

@author: Jialai_Zhu
'''
import sys
import os
from xml.dom import minidom
import string
import mufs
import time
def num2s(num):
    return "%d" % (num)
class xmlmaltree(object):
    def __init__(self, url, dir=None):
        self.url = url
        self.dir = dir
        self.doc = minidom.Document()
        self.parent = self.doc.createElement('root')
        self.parent.setAttribute('level', num2s(0))
        self.parent.setAttribute('time', time.ctime())
        self.root = self.parent
        self.doc.appendChild(self.root)    
    def appendw(self, node):
        self.append(node)
        self.toFile(self.dir)    
    def append(self, node):
        try:
            newleaf = self.doc.createElement('link')
            
            try:    newleaf.setAttribute('md5u', node.md5u)
            except: pass
            
            try:    newleaf.setAttribute('md5f', node.md5f)
            except: pass
            
            newleaf.setAttribute('type', node.tag)
            newleaf.setAttribute('url', node.url)
            newleaf.setAttribute('level', num2s(node.level))
            newleaf.setAttribute('code', node.code)

            
            parent = self.find_parent(node.level)
            parent.appendChild(newleaf)
            self.parent = newleaf
        except:
            pass   
        
    def get_level(self, element):
        level = element.getAttribute('level')
        return level
    def find_parent(self, level):
        parent = self.parent
        levelleaf = string.atoi(self.get_level(parent))   
        while levelleaf + 1 != (level):
           parent = parent.parentNode
           levelleaf = string.atoi(self.get_level(parent))
        return parent 
    def xml(self):
        return self.doc.toprettyxml(indent=" ")
 
    
    def toFile(self, dir=None):
        if dir == None:
            dir = self.dir
        fs = mufs.mufs(dir)
        fs.save(self.url, self.xml(), 'xml')

        
